package com.lcf.framework.handler;

import cn.hutool.json.JSONUtil;
import com.lcf.framework.model.R;
import com.lcf.framework.utils.UrlUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * 描述：全局请求返回拦截
 *
 * @author lcf
 * @since 2025/2/25 14:45
 */

@ControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    private static final List<String> IGNORE_URLS = List.of("/**/v3/api-docs/swagger-config", "/**/v3/api-docs");

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 将返回值封装成统一格式
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (UrlUtils.matchUrl(IGNORE_URLS, request.getURI().getPath())) {
            return body;
        }

        // 直接返回二进制流（如 Excel 文件）
        if (body instanceof byte[]) {
            return body;
        }

        if (body instanceof R) {
            return body;
        }

        // ‌如果 Controller 方法的返回值类型是 String‌，Spring 会优先选择 StringHttpMessageConverter（字符串转换器），
        // 它要求返回值必须是 String 类型，否则会抛出类型转换异常。
        if (body instanceof String) {
            return JSONUtil.toJsonStr(R.success(body));
        }

        return R.success(body);
    }
}
